package org.formal.common.base;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;

/**
 * 
 * SQL生成类
 * @author jiangyan
 *
 */
@SuppressWarnings("unchecked")
public class SqlProvider {
		/**
		 * 根据map构建insert语句
		 * @param tableName 表名
		 * @param param Map 参数集
		 * @return
		 */
		public  String insertMapSql(@Param("tableName")String tableName,Map<String,Object> param) {
			Map<String,Object> map = (Map<String,Object>) param.get("map"); 
			SQL sql = new SQL();
			sql.INSERT_INTO(tableName);
			for(Entry<String, Object> entry : map.entrySet()) {
				if(entry.getValue() != null) {
					sql.VALUES(entry.getKey(), entry.getValue().toString());
				}
			}
			return sql.toString();
		}
		
		/**
		 * 根据map构建insert语句
		 * @param tableName 表名
		 * @param param Map 参数集
		 * @return
		 */
		public  String insertListMapSql(@Param("tableName")String tableName,Map<String,Object> param) {  
			List<Map<String,Object>> list = (List<Map<String,Object>>) param.get("list"); 
		        int index = 0;
		        StringBuilder pSql = new StringBuilder();
		        for(Map<String,Object> map : list) {
		        	if(index == 0) {
		        		SQL sql = new SQL();
		      	        sql.INSERT_INTO(tableName);
		        		Set<String> keys = map.keySet();
		        		sql.INTO_COLUMNS( keys.toArray(new String[keys.size()]) );
		        		sql.INTO_VALUES(map.values().toArray(new String[map.size()]));
		        		pSql.append(sql.toString());
		        		index = 1;
		        	}else {
		        		pSql.append(", (");
		        		map.entrySet().stream().forEach(entry->{
		        			pSql.append(entry.getValue());
		        			pSql.append(",");
		        		});
		        		pSql.deleteCharAt(pSql.length()-1);
		        		pSql.replace(pSql.length()-1, pSql.length(), ") ");
		        	}
		        }
		        return pSql.toString();
	    }  

}
